use specs::world::Index;
use specs::{ReadStorage, Entities, WriteStorage, System};
use std::sync::mpsc::Receiver;
use crate::res::velocity_storage::Velocity;
use crate::res::overlord_storage::Overlord;

pub struct SetVelocityMessage {
    entity_id: Index,
    velocity: Velocity,
    who: Index,
}

impl SetVelocityMessage {
    pub fn new(entity_id: Index, velocity: Velocity, who: Index) -> Self {
        SetVelocityMessage{
            entity_id,
            velocity,
            who,
        }
    }
}

pub struct SetVelocitySystem {
    rc: Receiver<SetVelocityMessage>,
}

impl SetVelocitySystem {
    pub fn new(rc: Receiver<SetVelocityMessage>) -> Self {
        SetVelocitySystem {
            rc,
        }
    }
}

impl<'a> System<'a> for SetVelocitySystem {
    type SystemData = (
        Entities<'a>,
        WriteStorage<'a, Velocity>,
        ReadStorage<'a, Overlord>
    );

    fn run(&mut self, data: Self::SystemData) {
        let (entities, mut velocity_storage, overlord_storage) = data;

        let received = self.rc.try_recv();

        if let Ok(set) = received {
            let entity = entities.entity(set.entity_id);
            let who_entity = entities.entity(set.who);

            if let Some(overlord) = overlord_storage.get(entity) {
                if overlord.0 == set.who {
                    if let Some(velocity) = velocity_storage.get_mut(entity) {
                        *velocity = set.velocity;
                    }
                }
            }
        }
    }
}
